<template>
  <el-drawer
    ref="drawerBox"
    v-bind="$attrs"
    :wrapper-closable="true"
    :close-on-press-escape="false"
    :title="title"
    :size="showMobilePage?'100%':'80%'"
    append-to-body
    v-on="$listeners"
  >
    <div class="drawer-content">
      <FilterInput
        v-model="filterInput"
        :filter-list="filterList"
        show-search-btn
        line-feed
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
      />
      <div :style="multiple?'':{marginTop: '17px'}" class="table-list">
        <div v-loading="listLoading">
          <template v-if="(isAllTab && list.items.length > 0) || (isSelectedTab && selectedData.length > 0)">
            <u-table
              ref="tableRef"
              :data="isAllTab?list.items:selectedData"
              :row-class-name="(data) => tableRowClassName(data)"
              :height="setTableHeight"
              :border="true"
              class="fb-table"
              beautify-table
              header-drag-style
              header-cell-class-name="order-data-header-cell"
              element-loading-text="加载中..."
              empty-text="暂无数据"
              fit
              select-callback
              hightlight-current-rowref="tableRef"
              @sort-change="sortMethod"
              @select="selectTable"
              @select-all="selectTable">
              <u-table-column
                v-if="multiple"
                fixed="left"
                align="center"
                type="selection"
                width="50"
              />
              <u-table-column v-else fixed="left" align="left" label="" min-width="50">
                <template slot-scope="scope">
                  <el-radio v-model="singleSelectId" :label="scope.row.id" @change="changeRadio($event, scope.row)"><span/></el-radio>
                </template>
              </u-table-column>
              <u-table-column align="left" label="结算单号" width="185" label-class-name="diy-cell" class-name="diy-cell">
                <template slot-scope="scope" slot="header">
                  <div class="diyHeader">{{ scope.column.label }}</div>
                </template>
                <template slot-scope="scope">
                  <processSn :is-expedited="scope.row.isExpedited">
                    <span style="cursor:pointer;color:#406EFF" @click="toCheck(scope.row)">{{ scope.row.supplierNum || '--' }}</span>
                  </processSn>
                </template>
              </u-table-column>
              <u-table-column align="left" label="结算名称" width="240">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.settleName" />
                </template>
              </u-table-column>
              <u-table-column align="right" label="结算金额(元)" width="130" sortable="custom" prop="settlementAmount">
                <template slot-scope="scope">
                  <PriceColumn :real-val="scope.row.settlementAmount" :price="scope.row.settlementAmount / 100" />
                </template>
              </u-table-column>
              <u-table-column align="right" label="实付金额(元)" width="130">
                <template slot-scope="scope">
                  <PriceColumn :real-val="scope.row.actualAmount" :price="scope.row.actualAmount / 100" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="成本来源" width="120">
                <template slot-scope="scope">
                  <ToolTip v-if="!scope.row.isNotOrder" :content="scope.row.costBelong | supplierCostBelong" />
                  <div v-else>非订单</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="成本项" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.costItemName" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="当前节点" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.reviewRole" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="当前处理人" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.currentRole" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="审批进度" width="120">
                <template slot-scope="scope">
                  <el-tooltip v-if="scope.row.reviewProgress" :open-delay="800" placement="top-start" effect="dark">
                    <div slot="content" style="max-width:200px;"> {{ scope.row.reviewProgress }}</div>
                    <div class="ellipsis">{{ scope.row.reviewProgress }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="关联订单">
                <template slot-scope="scope">
                  <span>{{ scope.row.linkOrder || '--' }}</span>
                </template>
              </u-table-column>
              <u-table-column align="left" label="供应商" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.supplier" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="状态">
                <template slot-scope="scope">
                  <div style="display:flex;align-items:center">
                    <div :style="scope.row.listStatus === 4?{backgroundColor: '#31CC9C'}:{backgroundColor: '#FD8546'}" class="dot"/>
                    <span>{{ scope.row.listStatus | listStatus }}</span>
                  </div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="申请人">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.proposer" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="申请人部门" width="140">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.proposerDepartmentName" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="账户类型" width="120">
                <template slot-scope="scope">
                  {{ scope.row.accountType | accountTypeStatus }}
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建人">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.createUser" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建时间" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.createTime | format('YYYY/MM/DD') }}</span>
                </template>
              </u-table-column>
            </u-table>
          </template>
          <empty-placeholder v-else :text="'暂无数据'" style="margin-bottom: 24px" />
        </div>
        <fixed-pagination v-if="isAllTab" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!multiple && !singleSelect.id || multiple && !hasSeleted" size="small" type="primary" class="related-btn" @click="confirmSelectData">确定</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
          </div>
          <el-pagination
            v-if="isAllTab"
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
        <fixed-pagination v-if="curTabName == 'selected'" class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!hasSeleted" size="small" type="primary" class="related-btn" @click="confirmSelectData">{{ confirmText }}</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
          </div>
          <el-pagination
            v-show="selectedData.length > 0"
            :current-page="selectedPage"
            :page-size="selectedPerPage"
            :total="selectedData.length"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>

<script>
// components
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ResourceInfo from '@/components/ResourceInfo';
import PlatformIcon from '@/components/Common/platformIcon';
// api
import { getDepartmentAll, costList } from '@/api/config';
import { getIssueOurTitleList } from '@/api/issueInvoice';
import { deptList } from '@/api/select';
import { getSupplierList, getSupplierTab } from '@/api/supplier';
// tools
import { accountTypeStatus, supplierCostBelong, listStatus } from '@/filters/status';
import { format } from '@/filters/date';
import { CURRENT_NODE_MODULE } from '@/utils/const';
import TableAdaptive from '@/mixins/tableAdaptive';
import options from '@/views/legal/module/options';
import axios from 'axios';
import tableSelections from '@/mixins/tableSelections';
import { paramsAryToStr } from '@/utils/paramsFormat';
import { mapState } from 'vuex';
import { expeditedOptions } from '@/filters/status';

export default {
  name: 'RelatedContract',
  filters: {
    accountTypeStatus,
    supplierCostBelong,
    listStatus,
    format
  },
  components: {
    EmptyPlaceholder,
    ResourceInfo,
    PlatformIcon
  },
  mixins: [tableSelections, TableAdaptive],
  props: {
    title: {
      type: String,
      default: '选择历史审批'
    },
    confirmText: {
      type: String,
      default: '确定'
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      filterInput: {},
      otherFilterInput: {},
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      selectedPage: 1,
      selectedPerPage: 20,
      sortType: '',
      sortName: '',
      listLoading: false,
      singleSelect: {
        id: ''
      }, // 单选
      options,
      idKey: 'id', // 多选框参数
      isUmyTable: true,
      tableRefName: 'tableRef',
      curTabName: 'all',
      deptTreeList: [],
      selectedData: [],
      otherList: [],
      rangeKeyArr: [{
        attr: 'contractEffectDate',
        start: 'contractEffectStartDate',
        end: 'contractEffectEndDate',
        type: 'round'
      }, {
        attr: 'contractAmount',
        start: 'contractAmountMin',
        end: 'contractAmountMax',
        type: 'moneyFixedTwo'
      }],
      updateId: null,
      tableOutsideHeight: 175,
      cancelToken: null,
      subjectOptions: [],
      deptOption: [],
      invoiceOptions: [ // 发票状态下拉选项
        { value: 0, label: '已取得' },
        { value: 1, label: '未取得' },
        { value: 2, label: '无需发票' },
        { value: 3, label: '财务统一申请' },
        { value: 4, label: '业务统一申请' }
      ],
      costItem: null
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    arrayKeyArr() {
      return ['currentNode', 'costItemNames'];
    },
    isAllTab() {
      return this.curTabName === 'all';
    },
    isSelectedTab() {
      return this.curTabName === 'selected';
    },
    hasSeleted() {
      return this.selectedData.length > 0;
    },
    filterList() {
      return [
        { keyword: 'supplierNum', name: '结算单号', labelWidth: '96px', type: 'input' },
        { keyword: 'settleName', name: '结算名称', labelWidth: '96px', type: 'input' },
        { keyword: 'orderNum', name: '订单编号', labelWidth: '96px', type: 'input' },
        { keyword: 'supplier', name: '供应商名称', labelWidth: '96px', type: 'input' },
        { keyword: 'settleCreateUser', name: '结算单创建人', labelWidth: '96px', type: 'input' },
        { keyword: 'createUser', name: '审批单创建人', labelWidth: '96px', type: 'input' },
        { keyword: 'proposer', name: '审批单申请人', labelWidth: '96px', type: 'input' },
        { keyword: 'approvalUser', name: '审批单审批人', labelWidth: '96px', type: 'input' },

        { keyword: 'currentRole', name: '当前处理人', labelWidth: '96px', type: 'input' },
        { keyword: 'reviewNum', name: '审批单号', labelWidth: '96px', type: 'input' },
        { keyword: 'costNum', name: '成本编号', labelWidth: '96px', type: 'input' },

        { keyword: 'settleAmount', labelWidth: '96px', name: '结算金额', type: 'inputRange' },
        { keyword: 'proposerDepartment', name: '申请人部门', isSearch: true, type: 'select', options: this.deptOption },
        { keyword: 'paymentBelong', name: '款项归属', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'costBelong', name: '成本来源', type: 'select', options: [
          { value: 0, label: '渠道订单' },
          { value: 1, label: '项目订单' },
          { value: 2, label: '商务订单' },
          { value: 3, label: '营销授权' },
          { value: 5, label: '项目渠道单' },
          { value: 9, label: '非订单' }
        ] },
        { keyword: 'accountType', name: '账户类型', type: 'select', options: [
          { value: 1, label: '第三方账户' },
          { value: 2, label: '对公银行账户' },
          { value: 3, label: '对公其他账户' }
        ] },
        { keyword: 'invioce', name: '发票', type: 'select', options: this.invoiceOptions },
        { keyword: 'invioceStatus', name: '发票状态', type: 'select', options: [
          { value: 0, label: '已填写' },
          { value: 1, label: '未填写' }
        ] },
        { keyword: 'costItemNames', name: '成本项', type: 'mulSelect', isSearch: true, options: this.costItem },
        {
          keyword: 'currentNode',
          name: '当前节点',
          type: 'loadMoreSelect',
          valueName: 'name',
          directShow: true,
          multiple: true,
          extendParams: { type: CURRENT_NODE_MODULE.SUPPLIER },
          labelName: 'name',
          placeholder: '当前节点',
          apiUrl: 'admin/common/currentNodes',
          searchkeyword: 'keyword'
        },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        { keyword: 'examinePayStatus', name: '付款状态', type: 'select', options: [{ value: 0, label: '未付款' }, { value: 1, label: '已付款' }] }
      ];
    },
    selectedTableData() {
      return this.selectedData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    singleSelectId: {
      get() {
        return this.singleSelect.id;
      },
      set(id) {
        //
      }
    }
  },
  created() {
    this.getDeptList();
    this.getCostItemList();
    this.getSubJectOptions();
    this.fetchData(false);
    this.init();
  },
  methods: {
    getSubJectOptions() {
      this.subjectOptions = [];
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.subjectOptions.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '所属公司'
            });
          });
        }
      });
    },
    toCheck(item) {
      const url = this.$router.resolve({
        name: 'supplierDetail',
        query: {
          settleId: item.id,
          id: item.supplierId,
          isSettle: true
        }
      });
      window.open(url.href, '_blank');
    },
    // 初始获取数据
    init(data) {
      this.queryDeptTreeList();
      this.singleSelect = data || {};
    },
    changeRadio(e, data) {
      this.singleSelect = data;
    },
    initSelectData(data = []) {
      this.selectedData = data;
      this.multipleSelectionAll = data;
    },
    async getDeptList() {
      const res = await deptList();
      res.data.forEach(i => {
        i.label = i.value;
        i.value = i.id;
      });
      this.deptOption = res.data;
    },
    update(id) {
      this.updateId = id;
      this.fetchData();
    },
    updateItem() {
      const item = this.list.items.filter(el => el.id === this.updateId)[0];
      this.$emit('updateItem', item);
      this.updateId = null;
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      if (this.curTabName === 'all') {
        this.fetchData();
      }
    },
    handleSelectData(e, row) {
      this.selectedData = e ? [row] : [];
      this.list.items.forEach(it => {
        it.checked = e ? it.id === row.id : false;
      });
    },
    handleSelectionChange(row) {
      this.$refs['tableRef'].clearSelection();
      this.list.items.forEach(it => {
        it.checked = row.checked ? false : it.id === row.id;
      });
      this.selectedData = [row];
    },
    handleLimit(row) {
      if (!row.contractEffectEndDate && !row.contractEffectStartDate) {
        return '/';
      }
      return '-';
    },
    // fitter
    queryClick() {
      if (this.isSelectedTab) this.curTabName = 'all';
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      this.filterInput = {};
      this.queryClick();
    },
    // 翻页
    handleData(tableData) {
      return tableData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    handleSizeChange(val) {
      if (this.curTabName === 'all') {
        this.perPage = val;
        this.fetchData(true);
      } else if (this.isSelectedTab) {
        this.selectedPerPage = val;
        this.setSelectRow(this.selectedTableData);
      }
    },
    handleCurrentChange(toPage) {
      if (this.curTabName === 'all') {
        this.page = toPage;
        this.fetchData();
      } else if (this.isSelectedTab) {
        this.selectedPage = toPage;
        this.setSelectRow(this.selectedTableData);
      }
    },
    handelParams() {
      const filterInput = JSON.parse(JSON.stringify(this.filterInput));
      const params = { ...filterInput, page: this.page, perPage: this.perPage };
      params.isShowMe = this.isShowMe;
      params.isMyApproval = this.isMyApproval;
      params.isMyPending = this.isMyPending;
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      paramsAryToStr(this.arrayKeyArr, params);
      if (params.settleAmount && Array.isArray(params.settleAmount) && params.settleAmount.length === 2) {
        params.settleAmountBegin = params.settleAmount[0];
        params.settleAmountEnd = params.settleAmount[1];
      }
      delete params.settleAmount;
      if (params.paymentBelong && Array.isArray(params.paymentBelong))params.paymentBelong = params.paymentBelong.join(',');
      return params;
    },
    // 获取列表数据
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.handelParams();
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();
      this.cancelToken = source;
      this.listLoading = true;
      this.getTabList();
      if (this.$route.query.settleId) {
        params.excludeId = this.$route.query.settleId;
      }
      getSupplierList(params, source.token).then(res => {
        this.isInit = false;
        if (res.code === 200) {
          this.list = res.data;
          if (!this.isSelectedTab) this.setSelectRow(res.data.items);
        }
        this.list.isInint = false;
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    async getTabList() {
      try {
        const params = this.handelParams();
        const result = await getSupplierTab(params);
        if (result.code === 200) {
          this.tabList = result.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    getCostItemList() {
      costList({ getAll: 1 }).then(res => {
        if (res.data) {
          const costItem = res.data.items;
          const costItemList = [];
          costItem.forEach(item => {
            if (!costItemList.find(cost => cost.label === item.costName)) {
              const obj = {
                value: item.costName,
                label: item.costName
              };
              costItemList.push(obj);
            }
          });
          this.costItem = costItemList;
        }
      });
    },
    confirmSelectData() {
      const data = this.singleSelect;
      this.$emit('confirmSelectData', data);
    },
    // 保留数据
    tableSelectionChange(selection) {
      this.selectedData = selection;
      if (this.isSelectedTab) this.setSelectRow(this.selectedTableData);
    },
    // 申请部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    onBackClick() {
      this.$refs.drawerBox.closeDrawer();
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
::v-deep .el-badge__content{
  background: #FB5227;
}
::v-deep .el-badge__content{
  margin-top: 18px;
}
.tip {
  color: #999;
  font-size: 13px;
  margin-left: 20px;;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .table-list {
    &::v-deep {
     .el-table__header {
        .el-checkbox__inner {
          position: relative;
          left: -2px;
        }
      }
    }
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      align-items: center;
      .related-btn {
        margin-left: 20px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    ::v-deep .pagination-flex {
      position: absolute;
      width: 100% !important;
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
</style>
